import 'dart:async';

import 'package:flutter/services.dart';
import 'package:hui_location/bean/loc_data_bean.dart';

import 'bean/addr_data_bean.dart';
import 'constant/constant_util.dart';

class HuiLocation {
  late Stream<LocData?> _onLocationChanged;
  static const MethodChannel _channel = const MethodChannel('hui_location');
  static const EventChannel _eventChannel =
      const EventChannel('sqh.rr/location');

  static Future<String?> get platformVersion async {
    final String? version = await _channel.invokeMethod('getPlatformVersion');
    return version;
  }

  //使用MethodChannel通信  result.success只能调用一次
  static Future<LocData?> get locationData async {
    // Map<String, double> value = await _channel.invokeMethod('getLocationData');
    var response = await _channel.invokeMethod('getLocationData');
    //处理type '_InternalLinkedHashMap<Object?, Object?>' is not a subtype of type 'Map
    //new Map<String, double>.from(response)
    LocData? version;
    if (response == null) {
      version = null;
    } else {
      Map<String, double> value = new Map<String, double>.from(response);
      version = LocData.fromJson(value);
    }

    return version;
  }

  ///使用EventChannel通信  result.success可以调用多次
  ///经纬度获取入口
  Stream<LocData?> eventLocationData(String type) {
    _onLocationChanged = _eventChannel
        .receiveBroadcastStream([type]).map<LocData>(
            (event) => LocData.fromJson(event.cast<String, double>()));
    return _onLocationChanged;
  }

  ///地理位置逆向解析
  ///使用MethodChannel通信
  ///lon:经度  lat:纬度
  Future<AddressData?> geocoderData(double lon, double lat) async {
    //Map<String, double> args = {"lon": lon, "lat": lat};
    var response = await _channel
        .invokeMethod(ConstantUtil.geocoderChannelName, [lon, lat]);
    Map<String, String> value = new Map<String, String>.from(response);
    AddressData? addressData = AddressData.fromJson(value);

    return addressData;
  }
}
